#include<iostream>
#include<pthread.h>
#include<string>
#include<vector>
#include<unistd.h>

#define NUM 5
int cnt = 1000;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;

void* routine(void* args)
{
    std::string name = static_cast<const char*>(args);
    while (true)
    {
        pthread_mutex_lock(&glock);
        pthread_cond_wait(&gcond, &glock); // glock在pthread_cond_wait之前，会被自动释放掉
        std::cout << name << " 计算: " << cnt << std::endl;
        cnt++;
        pthread_mutex_unlock(&glock);
    }
    
}

int main()
{
    std::vector<pthread_t> threads;
    for(int i=0;i<NUM;i++)
    {
        pthread_t tid;
        char id[64];
        snprintf(id,sizeof(id),"thread-%d",i);
        int n = pthread_create(&tid,nullptr,routine,id);
        if(n!=0)
            continue;
        threads.push_back(tid);
        sleep(1);
    }

    while(true)
    {
        // std::cout << "唤醒所有线程... " << std::endl;
        // pthread_cond_broadcast(&gcond);
        std::cout << "唤醒一个线程... " << std::endl;
        pthread_cond_signal(&gcond);
        sleep(1);
    }

    for(int i=0;i<NUM;i++)
    {
        pthread_join(threads[i],nullptr);
    }
    
    return 0;
}